<template>
  <div class="messages-container">
    <!-- 页面标题和宣传文案 -->
    <div class="page-header">
      <h1 class="page-title">温馨消息中心</h1>
      <p class="page-subtitle">用心沟通，用爱守护 - 这里是您与家属、同事温暖交流的桥梁</p>
    </div>

    <!-- 消息统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon new-messages">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ unreadCount }}</div>
            <div class="stat-label">未读消息</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total-messages">
            <el-icon><Message /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ totalCount }}</div>
            <div class="stat-label">总消息数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon today-messages">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ todayCount }}</div>
            <div class="stat-label">今日消息</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filter.role" placeholder="按角色筛选" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="前台" value="reception"></el-option>
            <el-option label="家属" value="family"></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="护工" value="caregiver"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filter.status" placeholder="按状态筛选" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="未读" value="unread"></el-option>
            <el-option label="已读" value="read"></el-option>
          </el-select>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="loadMessages" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新消息
          </el-button>
          <el-button @click="markAllAsRead" :disabled="unreadCount === 0">
            <el-icon><Check /></el-icon>
            全部标记为已读
          </el-button>
          <el-button type="success" @click="showSendDialog = true">
            <el-icon><Promotion /></el-icon>
            发送消息
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 消息列表 -->
    <div class="messages-list">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>消息列表</span>
            <el-tag type="info">共 {{ filteredMessages.length }} 条消息</el-tag>
          </div>
        </template>
        
        <div v-if="filteredMessages.length === 0" class="empty-state">
          <el-empty description="暂无消息" :image-size="200">
            <p>当您收到新消息时，会在这里显示</p>
          </el-empty>
        </div>
        
        <div v-else class="message-items">
          <div 
            v-for="message in filteredMessages" 
            :key="message.id"
            class="message-item"
            :class="{ 'unread': !message.isRead }"
            @click="viewMessage(message)"
          >
            <div class="message-avatar">
              <el-avatar :size="40" :src="getAvatarByRole(message.senderRole)">
                {{ getRoleIcon(message.senderRole) }}
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">{{ message.senderName }}</span>
                <span class="sender-role" :class="getRoleClass(message.senderRole)">
                  {{ getRoleText(message.senderRole) }}
                </span>
                <span class="message-time">{{ formatTime(message.createTime) }}</span>
              </div>
              <div class="message-body">
                <p class="message-title">{{ message.title }}</p>
                <p class="message-preview">{{ message.content }}</p>
              </div>
            </div>
            <div class="message-status">
              <el-badge v-if="!message.isRead" is-dot class="badge-dot"></el-badge>
              <el-icon v-else class="read-icon"><Check /></el-icon>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 消息详情弹窗 -->
    <el-dialog 
      v-model="showDetail" 
      :title="currentMessage?.title" 
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-header">
          <div class="sender-info">
            <el-avatar :size="50" :src="getAvatarByRole(currentMessage.senderRole)">
              {{ getRoleIcon(currentMessage.senderRole) }}
            </el-avatar>
            <div class="sender-details">
              <div class="sender-name">{{ currentMessage.senderName }}</div>
              <div class="sender-role" :class="getRoleClass(currentMessage.senderRole)">
                {{ getRoleText(currentMessage.senderRole) }}
              </div>
            </div>
          </div>
          <div class="message-time">{{ formatTime(currentMessage.createTime) }}</div>
        </div>
        
        <div class="detail-content">
          <p>{{ currentMessage.content }}</p>
        </div>
        
        <div v-if="currentMessage.relatedElder" class="related-elder">
          <el-tag type="info">
            <el-icon><User /></el-icon>
            相关长者：{{ currentMessage.relatedElder }}
          </el-tag>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showDetail = false">关闭</el-button>
        <el-button v-if="currentMessage && !currentMessage.isRead" type="primary" @click="markAsRead(currentMessage)">
          标记为已读
        </el-button>
      </template>
    </el-dialog>

    <!-- 发送消息弹窗 -->
    <el-dialog 
      v-model="showSendDialog" 
      title="发送消息"
      width="600px"
      :close-on-click-modal="false"
      @closed="resetSendForm"
    >
      <el-form 
        :model="sendForm" 
        :rules="sendFormRules" 
        ref="sendFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="接收者角色" prop="receiverRole">
          <el-select 
            v-model="sendForm.receiverRole" 
            placeholder="请选择接收者角色"
            style="width: 100%"
            @change="handleReceiverRoleChange"
          >
            <el-option label="前台" value="reception"></el-option>
            <el-option label="家属" value="family"></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="护工" value="caregiver"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="接收者" prop="receiverId">
          <el-select 
            v-model="sendForm.receiverId" 
            placeholder="请选择接收者"
            style="width: 100%"
            :loading="formLoading"
            filterable
          >
            <el-option 
              v-for="receiver in receiverOptions" 
              :key="receiver.id"
              :label="receiver.name"
              :value="receiver.id"
            >
              <div style="display: flex; align-items: center;">
                <el-avatar :size="24" :src="receiver.avatar" style="margin-right: 8px;">
                  {{ getRoleIcon(sendForm.receiverRole) }}
                </el-avatar>
                <span>{{ receiver.name }}</span>
                <el-tag size="small" style="margin-left: 8px;">
                  {{ getRoleText(sendForm.receiverRole) }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联长者" prop="relatedElderId">
          <el-select 
            v-model="sendForm.relatedElderId" 
            placeholder="请选择关联长者（可选）"
            style="width: 100%"
            clearable
            filterable
          >
            <el-option 
              v-for="elder in elderOptions" 
              :key="elder.id"
              :label="elder.name"
              :value="elder.id"
            >
              <div style="display: flex; align-items: center;">
                <el-avatar :size="24" :src="elder.avatar" style="margin-right: 8px;">
                  {{ elder.name.charAt(0) }}
                </el-avatar>
                <span>{{ elder.name }}</span>
                <el-tag size="small" style="margin-left: 8px;">
                  {{ elder.age }}岁
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="消息标题" prop="title">
          <el-input 
            v-model="sendForm.title" 
            placeholder="请输入消息标题"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="消息内容" prop="content">
          <el-input 
            v-model="sendForm.content" 
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showSendDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="sendMessage" 
          :loading="formLoading"
          :disabled="!sendForm.receiverId"
        >
          发送消息
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound, Message, Calendar, Refresh, Check, User, Promotion, Edit, Search, Plus, Delete } from '@element-plus/icons-vue'

// 响应式数据
const messages = ref([])
const loading = ref(false)
const showDetail = ref(false)
const currentMessage = ref(null)
const showSendDialog = ref(false)
const filter = ref({
  role: '',
  status: ''
})

// 发送消息表单
const sendForm = ref({
  receiverRole: '',
  receiverId: '',
  title: '',
  content: '',
  relatedElderId: ''
})

// 表单验证规则
const sendFormRules = {
  receiverRole: [
    { required: true, message: '请选择接收者角色', trigger: 'change' }
  ],
  receiverId: [
    { required: true, message: '请选择接收者', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

// 接收者选项
const receiverOptions = ref([])
const elderOptions = ref([])
const formLoading = ref(false)
const sendFormRef = ref()

// 模拟数据
const mockMessages = [
  {
    id: 1,
    title: '新入住长者分配通知',
    content: '您好！新入住的长者张三已分配给您照护，请及时查看长者信息并提供关怀服务。',
    senderName: '前台李小姐',
    senderRole: 'reception',
    createTime: new Date('2025-10-02 10:30:00'),
    isRead: false,
    relatedElder: '张三'
  },
  {
    id: 2,
    title: '关于我父亲近况的询问',
    content: '您好，我是王大爷的儿子。想了解一下我父亲最近在养老院的情况，他身体还好吗？',
    senderName: '王先生',
    senderRole: 'family',
    createTime: new Date('2025-10-02 09:15:00'),
    isRead: true,
    relatedElder: '王大爷'
  },
  {
    id: 3,
    title: '月度工作安排提醒',
    content: '各位护工请注意，本月的工作安排已更新，请及时查看并安排好您的照护计划。',
    senderName: '管理员',
    senderRole: 'admin',
    createTime: new Date('2025-10-01 16:45:00'),
    isRead: true
  },
  {
    id: 4,
    title: '感谢您的细心照护',
    content: '非常感谢您对我母亲的细心照顾，她最近精神状态很好，我们全家都很感激！',
    senderName: '李女士',
    senderRole: 'family',
    createTime: new Date('2025-09-30 14:20:00'),
    isRead: true,
    relatedElder: '李奶奶'
  }
]

// 计算属性
const unreadCount = computed(() => messages.value.filter(msg => !msg.isRead).length)
const totalCount = computed(() => messages.value.length)
const todayCount = computed(() => {
  const today = new Date().toDateString()
  return messages.value.filter(msg => new Date(msg.createTime).toDateString() === today).length
})

const filteredMessages = computed(() => {
  let filtered = messages.value
  
  if (filter.value.role) {
    filtered = filtered.filter(msg => msg.senderRole === filter.value.role)
  }
  
  if (filter.value.status === 'unread') {
    filtered = filtered.filter(msg => !msg.isRead)
  } else if (filter.value.status === 'read') {
    filtered = filtered.filter(msg => msg.isRead)
  }
  
  return filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
})

// 方法
const loadMessages = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    messages.value = [...mockMessages]
    ElMessage.success('消息加载成功')
  } catch (error) {
    ElMessage.error('消息加载失败')
  } finally {
    loading.value = false
  }
}

const viewMessage = (message) => {
  currentMessage.value = message
  showDetail.value = true
  if (!message.isRead) {
    markAsRead(message)
  }
}

const markAsRead = (message) => {
  message.isRead = true
  ElMessage.success('消息已标记为已读')
}

const markAllAsRead = () => {
  messages.value.forEach(msg => { msg.isRead = true })
  ElMessage.success('所有消息已标记为已读')
}

const getAvatarByRole = (role) => {
  const avatars = {
    reception: '/avatars/reception.png',
    family: '/avatars/family.png',
    admin: '/avatars/admin.png'
  }
  return avatars[role] || '/avatars/default.png'
}

const getRoleIcon = (role) => {
  const icons = {
    reception: '前',
    family: '家',
    admin: '管'
  }
  return icons[role] || '用'
}

const getRoleText = (role) => {
  const texts = {
    reception: '前台',
    family: '家属',
    admin: '管理员'
  }
  return texts[role] || '用户'
}

const getRoleClass = (role) => {
  return `role-${role}`
}

const formatTime = (time) => {
  const now = new Date()
  const msgTime = new Date(time)
  const diff = now - msgTime
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return msgTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return msgTime.toLocaleDateString('zh-CN')
  }
}

// 发送消息相关方法
const handleReceiverRoleChange = async (role) => {
  sendForm.value.receiverId = ''
  receiverOptions.value = []
  
  if (!role) return
  
  formLoading.value = true
  try {
    // 模拟根据角色获取接收者列表
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const mockReceivers = {
      reception: [
        { id: 1, name: '李前台', avatar: '/avatars/reception1.png' },
        { id: 2, name: '王前台', avatar: '/avatars/reception2.png' }
      ],
      family: [
        { id: 1, name: '张先生', avatar: '/avatars/family1.png' },
        { id: 2, name: '李女士', avatar: '/avatars/family2.png' },
        { id: 3, name: '王先生', avatar: '/avatars/family3.png' }
      ],
      admin: [
        { id: 1, name: '王管理员', avatar: '/avatars/admin1.png' },
        { id: 2, name: '刘管理员', avatar: '/avatars/admin2.png' }
      ],
      caregiver: [
        { id: 1, name: '张护工', avatar: '/avatars/caregiver1.png' },
        { id: 2, name: '李护工', avatar: '/avatars/caregiver2.png' },
        { id: 3, name: '王护工', avatar: '/avatars/caregiver3.png' }
      ]
    }
    
    receiverOptions.value = mockReceivers[role] || []
  } catch (error) {
    ElMessage.error('获取接收者列表失败')
  } finally {
    formLoading.value = false
  }
}

const loadElderOptions = async () => {
  try {
    // 模拟获取长者列表
    await new Promise(resolve => setTimeout(resolve, 300))
    
    elderOptions.value = [
      { id: 1, name: '张大爷', age: 78, avatar: '/avatars/elder1.png' },
      { id: 2, name: '李大妈', age: 82, avatar: '/avatars/elder2.png' },
      { id: 3, name: '王爷爷', age: 85, avatar: '/avatars/elder3.png' },
      { id: 4, name: '赵奶奶', age: 79, avatar: '/avatars/elder4.png' },
      { id: 5, name: '刘大爷', age: 76, avatar: '/avatars/elder5.png' }
    ]
  } catch (error) {
    ElMessage.error('获取长者列表失败')
  }
}

const sendMessage = async () => {
  if (!sendFormRef.value) return
  
  try {
    await sendFormRef.value.validate()
    formLoading.value = true
    
    // 模拟发送消息
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建新消息
    const newMessage = {
      id: Date.now(),
      title: sendForm.value.title,
      content: sendForm.value.content,
      senderName: '当前用户', // 这里应该从用户信息获取
      senderRole: 'caregiver', // 这里应该从用户信息获取
      createTime: new Date(),
      isRead: false,
      relatedElder: elderOptions.value.find(elder => elder.id === sendForm.value.relatedElderId)?.name || ''
    }
    
    // 添加到消息列表
    messages.value.unshift(newMessage)
    
    ElMessage.success('消息发送成功')
    showSendDialog.value = false
    resetSendForm()
    
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('消息发送失败')
    }
  } finally {
    formLoading.value = false
  }
}

const resetSendForm = () => {
  sendForm.value = {
    receiverRole: '',
    receiverId: '',
    title: '',
    content: '',
    relatedElderId: ''
  }
  receiverOptions.value = []
  elderOptions.value = []
  
  if (sendFormRef.value) {
    sendFormRef.value.clearValidate()
  }
}

// 生命周期
onMounted(() => {
  loadMessages()
  loadElderOptions()
})
</script>

<style scoped>
.messages-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 60px);
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 2.5rem;
  color: #2c3e50;
  margin-bottom: 10px;
  font-weight: 300;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #7f8c8d;
  font-weight: 300;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 15px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.new-messages {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}

.stat-icon.total-messages {
  background: linear-gradient(135deg, #4ecdc4, #44a08d);
}

.stat-icon.today-messages {
  background: linear-gradient(135deg, #45b7d1, #96c93d);
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1;
}

.stat-label {
  color: #7f8c8d;
  font-size: 0.9rem;
  margin-top: 5px;
}

.filter-toolbar {
  background: white;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.messages-list {
  background: white;
  border-radius: 10px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

.message-items {
  max-height: 600px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.message-item:hover {
  background: #f8f9fa;
  transform: translateX(5px);
}

.message-item.unread {
  background: #f0f8ff;
  border-left: 4px solid #1890ff;
}

.message-avatar {
  margin-right: 15px;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 10px;
}

.sender-name {
  font-weight: bold;
  color: #2c3e50;
}

.sender-role {
  font-size: 0.8rem;
  padding: 2px 8px;
  border-radius: 12px;
  color: white;
}

.role-reception {
  background: #e74c3c;
}

.role-family {
  background: #3498db;
}

.role-admin {
  background: #9b59b6;
}

.message-time {
  color: #95a5a6;
  font-size: 0.8rem;
}

.message-title {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
  font-size: 1rem;
}

.message-preview {
  color: #7f8c8d;
  font-size: 0.9rem;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.message-status {
  display: flex;
  align-items: center;
  margin-left: 15px;
}

.badge-dot {
  --el-badge-bg-color: #1890ff;
}

.read-icon {
  color: #52c41a;
  font-size: 18px;
}

.message-detail {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.sender-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.sender-details {
  display: flex;
  flex-direction: column;
}

.sender-details .sender-name {
  font-size: 1.2rem;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.detail-content {
  padding: 20px 0;
  line-height: 1.6;
  color: #2c3e50;
  font-size: 1rem;
}

.related-elder {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .messages-container {
    padding: 10px;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .filter-toolbar .el-col {
    margin-bottom: 10px;
  }
  
  .message-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .detail-header {
    flex-direction: column;
    gap: 15px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-item {
  animation: fadeIn 0.3s ease;
}

.stat-card {
  animation: fadeIn 0.5s ease;
}

/* 滚动条样式 */
.message-items::-webkit-scrollbar {
  width: 6px;
}

.message-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.message-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
